<template>
  <div class="app-container">
    <!-- 1.一个用于获取上传文件的input，type="file"，并且监听onchange事件  -->
    <input type="file" accept="image/*" id="imgReader" class="inputFile" @change="loadingImg">

    <!-- 2.一个用于给Cropper.js覆盖使用的img  -->
    <img id="cropImg" style="width: 300px;height:300px;">
    <el-button type="primary" @click="uploadImg">上传图片</el-button>
    <!-- 3.两个用于预览的div  -->
    <el-button type="primary" @click="GetData">裁剪下载</el-button>
    <div style="margin-top: 10px;">
      <el-button type="primary" @click="radiate('+')">放大</el-button>
      <el-button type="primary" @click="radiate('-')">放小</el-button>
    </div>
    <div style="margin-top: 10px;">
      <el-button type="primary" @click="Rotation('+')">右旋转</el-button>
      <el-button type="primary" @click="Rotation('-')">左旋转</el-button>
    </div>
    <div style="margin-top: 10px;"><el-button type="primary" @click="custom('crop')">自定义裁剪</el-button></div>
    <div style="margin-top: 10px;"><el-button type="primary" @click="custom('move')">改为拖动</el-button></div>
    <div style="margin-top: 10px;">
      <el-button type="primary" @click="reset">重置</el-button>
    </div>
    <div class="previewBox"></div>
    <div class="previewBoxRound"></div>
  </div>
</template>

<script>
//引入Cropper.js
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';

let CROPPER = null; //创建一个cropper的全局对象

export default {
  mixins: [],
  components: {},
  props: {},
  data() {
    return {
      sizeRate: 0,
      rotate: 0,
    };
  },
  computed: {},
  watch: {},
  mounted() {},
  created() {},
  methods: {
    custom(type) {
      CROPPER.setDragMode(type);
    },
    Rotation(d) {
      if (d === '+') {
        CROPPER.rotate(45);
      }
      if (d === '-') {
        CROPPER.rotate(-45);
      }
    },
    radiate(d) {
      if (d === '+') {
        CROPPER.zoom(0.1);
      }
      if (d === '-') {
        CROPPER.zoom(-0.1);
      }
    },
    reset() {
      CROPPER.reset();
    },
    GetData() {
      //getCroppedCanvas方法可以将裁剪区域的数据转换成canvas数据
      CROPPER.getCroppedCanvas({
        maxWidth: 4096,
        maxHeight: 4096,
        fillColor: '#fff',
        imageSmoothingEnabled: true,
        imageSmoothingQuality: 'high',
      }).toBlob((blob) => {
        const url = window.URL.createObjectURL(new Blob([blob]));
        const link = document.createElement('a');

        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', 'photo.png');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    },
    uploadImg() {
      document.querySelector('#imgReader').click();
    },
    loadingImg(eve) {
      //读取上传文件
      let reader = new FileReader();
      if (event.target.files[0]) {
        //readAsDataURL方法可以将File对象转化为data:URL格式的字符串（base64编码）
        reader.readAsDataURL(eve.target.files[0]);
        reader.onload = (e) => {
          let dataURL = reader.result;
          //将img的src改为刚上传的文件的转换格式
          document.querySelector('#cropImg').src = dataURL;

          const image = document.getElementById('cropImg');

          //创建cropper实例-----------------------------------------
          CROPPER = new Cropper(image, {
            aspectRatio: 16 / 16,
            viewMode: 0,
            minContainerWidth: 500,
            minContainerHeight: 500,
            dragMode: 'move',
            preview: [
              document.querySelector('.previewBox'),
              document.querySelector('.previewBoxRound'),
            ],
          });
        };
      }
    },
  },
};
</script>

<style scoped lang="scss">
.inputFile {
  display: none;
}
.previewBox,
.previewBoxRound {
  box-shadow: 0 0 5px #adadad;
  width: 100px;
  height: 100px;
  margin-top: 30px;
  overflow: hidden; /*这个超出设置为隐藏很重要，否则就会整个显示出来了*/
}
.previewBoxRound {
  border-radius: 50%; /*设置为圆形*/
}
</style>